package com.mylearning.restful;


import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONObject;
import org.junit.Test;
		 
		 
		public class RESTServiceClient {
		   
			@Test
			public void REST() throws Exception {
		        try {
		        	System.out.println("Starting REST Test.....");
		        	URL url = new URL("https://api.twitter.com/1.1/direct_messages/new.json");
		    		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		    		conn.setDoOutput(true);
		    		conn.setRequestMethod("POST");
		    		conn.setRequestProperty("Content-Type", "application/json");
		            
		    		System.out.println("Getting JSON string......");		
		    		String input = getJSONObject();
		     		OutputStream os = conn.getOutputStream();
		    		os.write(input.getBytes());
		    		os.flush();
		            
		    		System.out.println("Starting REST Http connection....");
		    		
		    		if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
		    			throw new RuntimeException("Failed : HTTP error code : "
		    				+ conn.getResponseCode());
		    		}
		     
		    		System.out.println("REST Connection successful !");
		    		
		    		BufferedReader br = new BufferedReader(new InputStreamReader(
		    				(conn.getInputStream())));
		     
		    		String output;
		    		System.out.println("Output from Server .... \n");
		    		while ((output = br.readLine()) != null) {
		    			System.out.println(output);
		    		}
		     
		    		conn.disconnect();
		     
		    	  } catch (Exception e) {
		     
		    		System.out.println("Exception in REST:" + e.getMessage());
		     
		    	  } 
		        }	
		        	
	
	public String getJSONObject() throws Exception {
		 String string = "";
	    InputStream inpStream = new FileInputStream("E:\\Yuvaraj\\Testing\\Eclipse\\WorkSpace-JEE\\RESTful\\data\\JSONFile.txt");
        InputStreamReader inpReader = new InputStreamReader(inpStream);
        BufferedReader br = new BufferedReader(inpReader);
        String line;
        while ((line = br.readLine()) != null) {
            string += line + "\n";
        }
        br.close();
        JSONObject jsonObject = new JSONObject(string);
        System.out.println(jsonObject);
        return jsonObject.toString();

	}
		   
		        	


}
